package com.luboyan.CBillbill.service.user.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.luboyan.CBillbill.mapper.user.UserRefreshMapper;
import com.luboyan.CBillbill.dao.user.RefreshToken;
import com.luboyan.CBillbill.service.user.UserRefreshService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserRefreshServiceImpl implements UserRefreshService {

    @Autowired
    private UserRefreshMapper userRefreshMapper;

    /**
     * 登录时添加刷新token
     */
    @Override
    public void addRefreshTokenById(Long id, String refreshToken, Date date) {
        QueryWrapper<RefreshToken> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", id);
        Long rows = userRefreshMapper.selectCount(queryWrapper);
        if(rows>0){
            userRefreshMapper.delete(queryWrapper);
        }
        RefreshToken userRefresh = new RefreshToken();
        userRefresh.setRefreshToken(refreshToken);
        userRefresh.setCreateTime(date);
        userRefresh.setUserId(id);
        userRefreshMapper.insert(userRefresh);
    }

    /**
     * 根据id删除refreshToken
     */
    @Override
    public void deleteRefreshToken(String refreshToken) {
        userRefreshMapper.delete(new QueryWrapper<RefreshToken>()
                .eq("refreshToken", refreshToken));
    }

    /**
     * 获取refreshToken得详情
     */
    @Override
    public RefreshToken getRefreshToken(String refreshToken) {
        return userRefreshMapper.selectOne(new QueryWrapper<RefreshToken>()
                .eq("refreshToken", refreshToken));
    }
}
